package org.jeecg.modules.scm.controller;

import com.alibaba.fastjson.JSONObject;
import cpcn.dsp.demo.api.query.CompanyVerifyQuery;
import cpcn.dsp.demo.consts.DSPConsts;
import cpcn.dsp.demo.util.HttpsUtil;
import cpcn.dsp.institution.api.notice.NoticeRequest;
import cpcn.dsp.institution.api.notice.NoticeResponse;
import cpcn.dsp.institution.api.security.EncryptAndDecrypt;
import cpcn.dsp.institution.api.system.DSPInstitutionEnvironment;
import cpcn.dsp.institution.api.tx.corpquery.Tx1304Request;
import cpcn.dsp.institution.api.tx.corpquery.Tx1304Response;
import cpcn.dsp.institution.api.tx.personalinfo.Tx2324Request;
import cpcn.dsp.institution.api.tx.personalinfo.Tx2324Response;
import cpcn.dsp.institution.api.util.Base64;
import cpcn.dsp.institution.api.util.GUIDGenerator;
import cpcn.dsp.institution.api.util.QRCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/cpcn")
@Slf4j
@Api(tags = "企业认证测试")
public class CpcnController {


    public static String keystore_test = "./test.pfx";
    public static String publicKey_test = "./dsptest.cer";
    //private final CpcnService cpcnService = new CpcnService();

    @ApiOperation("receiveNoticePage")
    @PostMapping("/receiveNoticePage")
    public String receiveNoticePage(HttpServletRequest request, HttpServletResponse response) {
        log.info("前台回调");
        String message = request.getParameter("Message");
        String signature = request.getParameter("Signature");
        String dgtlenvlp = request.getParameter("Dgtlenvlp");
        String signSN = request.getParameter("SignSN");
        String encryptSN = request.getParameter("EncryptSN");
        //解析
        //1.初始化
        try {
            DSPInstitutionEnvironment.initialize(keystore_test, DSPConsts.myKeystorePassword_test, publicKey_test, DSPConsts.MSG_ENCRYPT_20);
            NoticeRequest noticeRequest = new NoticeRequest(message, signature, dgtlenvlp, signSN, encryptSN);
            String plainText = noticeRequest.getPlainText();
            String txCode = noticeRequest.getTxCode();
            String code = noticeRequest.getCode();
            String noticeMessage = noticeRequest.getMessage();
            System.out.println(noticeMessage);
            log.info(noticeMessage);
            log.info(noticeRequest.toString());

            //////////////////////////////////
            //////解析明文后商户自己实现逻辑/////
            /////////////////////////////////
            //接收页面通知，响应的内容将会在识别结果页面展示
            PrintWriter out = response.getWriter();
            out.write(plainText);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index.html";
    }

    @ApiOperation("receiveNoticeBackground")
    @PostMapping("/receiveNoticeBackground")
    public void receiveNoticeBackground(HttpServletRequest request, HttpServletResponse response) {
        log.info("后台回调");
        String message = request.getParameter("Message");
        String signature = request.getParameter("Signature");
        String dgtlenvlp = request.getParameter("Dgtlenvlp");
        String signSN = request.getParameter("SignSN");
        String encryptSN = request.getParameter("EncryptSN");
        //解析
        //1.初始化
        try {
            DSPInstitutionEnvironment.initialize(keystore_test, DSPConsts.myKeystorePassword_test, publicKey_test, DSPConsts.MSG_ENCRYPT_20);
            NoticeRequest noticeRequest = new NoticeRequest(message, signature, dgtlenvlp, signSN, encryptSN);
            String plainText = noticeRequest.getPlainText();
            String txCode = noticeRequest.getTxCode();
            String code = noticeRequest.getCode();
            String noticeMessage = noticeRequest.getMessage();
            System.out.println(plainText);
            log.info(noticeRequest.toString());
            ////////////////////////////////////////
            //////后台通知需要响应给数据服务SUCCESS/////
            ////////////////////////////////////////
            PrintWriter out = response.getWriter();
            BASE64Encoder encoder = new BASE64Encoder();
            String noticeResponse = NoticeResponse.getMessage();
            String data = encoder.encode(noticeResponse.getBytes("UTF-8"));
            out.write(data);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/test1304")
    @ApiOperation("test1304")
    public Result<JSONObject> test1304(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.初始化
        DSPInstitutionEnvironment.initialize(keystore_test, DSPConsts.myKeystorePassword_test, publicKey_test, DSPConsts.MSG_ENCRYPT_20);
        //1.1 encryptSN、signSN值不为空，说明初始化证书成功
        System.out.println(DSPInstitutionEnvironment.encryptSN);
        System.out.println(DSPInstitutionEnvironment.signSN);

        //2.生成请求明文
        Tx1304Request tx1304Request = new Tx1304Request();
        tx1304Request.setInstitutionID("100827");// 机构号由中金分配
        tx1304Request.setTxSN(GUIDGenerator.genGUID());
        tx1304Request.setOrgIdentificationType("20");
        tx1304Request.setOrganizationName("****有限公司");
        tx1304Request.setOrgIdentificationNumber("91110102551443078Q");
        tx1304Request.setName("张三");
        tx1304Request.setIdentificationType("0");
        tx1304Request.setIdentificationNumber("110101198001010037");
        tx1304Request.setRemark("1");//仅测试环境判断该字段1->不一致,2->未知，3->请求失败，其他->一致

        //报文处理
        tx1304Request.process();
        String plainText = tx1304Request.getRequestPlainText();
        System.out.println("请求明文：" + plainText);

        String reqMessage = tx1304Request.getRequestMessage();
        String reqSignature = tx1304Request.getRequestSignature();
        String requestDgtlEnvlp = tx1304Request.getRequestDgtlEnvlp();
        String requestSignSN = tx1304Request.getRequestSignSN();
        String requestEncryptSN = tx1304Request.getRequestEncryptSN();
        //生成参数
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("message", reqMessage);
        paramMap.put("signature", reqSignature);
        paramMap.put("dgtlenvlp", requestDgtlEnvlp);
        paramMap.put("signSN", requestSignSN);
        paramMap.put("encryptSN", requestEncryptSN);
        //生成请求参数
        String requestString = EncryptAndDecrypt.createLinkStringByGet(paramMap);
        System.out.println("请求密文：" + requestString);
        //请求接口
        String result = HttpsUtil.post(DSPConsts.TX_URL_TEST, requestString, null);
        System.out.println("响应密文：" + result);

        String respPlainText = null;
        String[] respMsg = result.split(",");
        if (respMsg.length == 1 && -1 == respMsg[0].indexOf(',')) {
            respPlainText = Base64.decode(respMsg[0], "UTF-8");
        } else if (respMsg.length == 5) {
            String responseMessage = respMsg[0];
            ;
            String responseSignature = respMsg[1];
            ;
            String responseDgtlEnvlp = respMsg[2];
            ;
            String respSignSN = respMsg[3];
            ;
            String respEncryptSN = respMsg[4];
            ;

            Tx1304Response tx1304Response = new Tx1304Response(responseMessage, responseSignature, responseDgtlEnvlp, respSignSN, respEncryptSN);
            respPlainText = tx1304Response.getResponsePlainText();
            if ("2000".equals(tx1304Response.getCode())) {
                String verification = tx1304Response.getVerification();
                System.out.println("验证结果" + verification);
            }
        }
        System.out.println("响应明文：" + respPlainText);
        JSONObject jsonObject = JSONObject.parseObject(respPlainText);
        return Result.OK(jsonObject);
    }

    @PostMapping("/test2324")
    @ApiOperation("test2324")
    public Result<?> test2324(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.初始化
        DSPInstitutionEnvironment.initialize(keystore_test, DSPConsts.myKeystorePassword_test, publicKey_test, DSPConsts.MSG_ENCRYPT_20);
        //1.1 encryptSN、signSN值不为空，说明初始化证书成功
        System.out.println(DSPInstitutionEnvironment.encryptSN);
        System.out.println(DSPInstitutionEnvironment.signSN);
        //2.生成请求明文
        JSONObject json = new JSONObject();
        Tx2324Request tx2324Request = new Tx2324Request();
        tx2324Request.setInstitutionID("100827");// 机构号由中金分配
        tx2324Request.setTxSN(GUIDGenerator.genGUID());
        tx2324Request.setName("张三");
        tx2324Request.setIdentificationNumber("110101198001010037");
        tx2324Request.setFrontUrl("http://212.64.69.165:9999/jeecg-scm/cpcn/receiveNoticePage");//需要更换为外网可以访问的ip
        tx2324Request.setFrontMethod("0");
        tx2324Request.setReturnImage("1");
        tx2324Request.setBackUrl("http://212.64.69.165:9999/jeecg-scm/cpcn/receiveNoticeBackground");//需要更换为外网可以访问的ip
        tx2324Request.setThreshold("");//默认为T5
        tx2324Request.setRemark("");//仅测试环境判断该字段1->不一致,2->未知，3->请求失败，其他->一致
        //报文处理
        tx2324Request.process();


        String plainText = tx2324Request.getRequestPlainText();
        System.out.println("请求明文：" + plainText);

        String reqMessage = tx2324Request.getRequestMessage();
        String reqSignature = tx2324Request.getRequestSignature();
        String requestDgtlEnvlp = tx2324Request.getRequestDgtlEnvlp();
        String requestSignSN = tx2324Request.getRequestSignSN();
        String requestEncryptSN = tx2324Request.getRequestEncryptSN();

        //生成参数
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("message", reqMessage);
        paramMap.put("signature", reqSignature);
        paramMap.put("dgtlenvlp", requestDgtlEnvlp);
        paramMap.put("signSN", requestSignSN);
        paramMap.put("encryptSN", requestEncryptSN);
        //生成请求参数
        String requestString = EncryptAndDecrypt.createLinkStringByGet(paramMap);
        System.out.println("请求密文：" + requestString);
        //请求接口
        String result = HttpsUtil.post(DSPConsts.TX_URL_TEST, requestString, null);
        System.out.println("响应密文：" + result);

        String responsePlainText = null;
        String[] respMsg = result.split(",");
        if (respMsg.length == 1 && -1 == respMsg[0].indexOf(',')) {
            responsePlainText = Base64.decode(respMsg[0], "UTF-8");
        } else if (respMsg.length == 5) {
            String responseMessage = respMsg[0];
            String responseSignature = respMsg[1];
            String responseDgtlEnvlp = respMsg[2];
            String respSignSN = respMsg[3];
            String respEncryptSN = respMsg[4];

            Tx2324Response tx2324Response = new Tx2324Response(responseMessage, responseSignature, responseDgtlEnvlp, respSignSN, respEncryptSN);
            responsePlainText = tx2324Response.getResponsePlainText();
            if ("2000".equals(tx2324Response.getCode())) {
                //响应中的URL是活体链接地址
                String url = tx2324Response.getUrl();
                //提供二维码生成方法。建议二维码大小为500，机构方可自己根据页面来调试生成的二维码大小
                String qrCode = QRCodeUtil.createQRCode(url, 500, 500);
                //此方法为生成携带logo的二维码链接，logo图片存放在SRC的同级目录下。
                String qrCodeWithLogo = QRCodeUtil.createQRCodeWithLogo(url, "cpcnLogo_02.jpg", 500, 500);
            }
        }
        System.out.println("响应明文：" + responsePlainText);
        JSONObject jsonObject = JSONObject.parseObject(responsePlainText);
        return Result.OK(jsonObject);
    }

    @ApiOperation("工商四要素验证测试")
    @PostMapping("/companyVerify")
    public Result<JSONObject> companyVerify(@RequestBody CompanyVerifyQuery query) {
        JSONObject jsonObject = null;
        try {
            //jsonObject = cpcnService.companyVerify(query);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("调用失败", null);
        }
        return Result.OK(jsonObject);
    }
}
